class Solution {
    int[] dr = new int[]{-1, 0, 1, 0};
    int[] dc = new int[]{0, -1, 0, 1};

    public int orangesRotting(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        Queue<Integer> queue = new LinkedList<Integer>();
        Map<Integer, Integer> depth = new HashMap<Integer, Integer>();
        for (int r = 0; r < m; r++){
            for (int c = 0; c < n; c++){
                if (grid[r][c] == 2){
                    int code = r*n+c;
                    queue.add(code);
                    depth.put(code, 0);
                }
            }
        }
        int ans = 0;
        while (!queue.isEmpty()){
            int code = queue.remove();
            int r = code / n, c = code % n;
            for (int k = 0; k < 4; ++k){
                int nr = r + dr[k];
                int nc = c + dc[k];
                if (0<=nr && nr<m && 0<=nc && nc<n && grid[nr][nc] == 1){
                    grid[nr][nc] = 2;
                    int ncode = nr * n + nc;
                    queue.add(ncode);
                    depth.put(ncode, depth.get(code)+1);
                    ans = depth.get(ncode);
                }
            }
        }

        for (int[] row: grid) {
            for (int v : row){
                if (v==1){
                    return -1;
                }
            }
        }
        return ans;
    }
}